package com.khiker.linklist;

import java.util.Arrays;

public class P23_MergeKLists {

    //    public ListNode mergeKLists(ListNode[] lists) {
//        if (lists == null || lists.length == 0) {
//            return null;
//        }
//        if (lists.length == 1) {
//            return lists[0];
//        }
//        ListNode head = lists[0];
//        int headIndex = 0;
//        for (int i = 0; i < lists.length; i++) {
//            if (lists[i] == null) {
//                continue;
//            }
//            if (head == null || head.val > lists[i].val) {
//                headIndex = i;
//                head = lists[i];
//            }
//        }
//        if (head == null) {
//            return null;
//        }
//        lists[headIndex] = head.next;
//        head.next = mergeKLists(lists);
//        return head;
//    }
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        if (lists.length == 1) {
            return lists[0];
        }
        ListNode head = lists[0];
        for (int i = 1; i < lists.length; i++) {
            head = mergeTwoLists(head, lists[i]);
        }
        return head;
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode head = l1.val > l2.val ? l2 : l1;
        ListNode cur = head;
        if (head == l2) {
            l2 = l2.next;
        } else {
            l1 = l1.next;
        }
        while (l1 != null && l2 != null) {
            if (l1.val >= l2.val) {
                cur.next = l2;
                cur = l2;
                l2 = l2.next;
            } else {
                cur.next = l1;
                cur = l1;
                l1 = l1.next;
            }
        }
        cur.next = l2 == null ? l1 : l2;
        return head;
    }
}
